package net.web.controller;


import com.alibaba.fastjson.JSONObject;
import net.web.entity.BlogView;
import net.web.service.BlogViewService;
import net.web.service.impl.BlogViewViewServiceImpl;
import net.web.tool.RespTool;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

// 在master分支写代码
@WebServlet("/blog/*")
public class BlogViewController extends HttpServlet {

    private BlogViewService blogViewService = new BlogViewViewServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        String reqType = uri.substring(uri.lastIndexOf("/") + 1);
        switch (reqType) {
            case "aj_sel_blog_by_all":
                aj_sel_blog_by_all(req, resp);
                break;
            case "aj_sel_blog_by_id":
                aj_sel_blog_by_id(req, resp);
            default:
                req.getRequestDispatcher("/404.jsp").forward(req, resp);
        }
    }

    private void aj_sel_blog_by_all(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<BlogView> blogViews = blogViewService.selBlogByAll();
        RespTool.writeResp(JSONObject.toJSONString(blogViews), resp);
    }

    private void aj_sel_blog_by_id(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        BlogView blogView = blogViewService.selBlogById(Integer.parseInt(id));
        RespTool.writeResp(JSONObject.toJSONString(blogView), resp);
    }


}
